package com.yusys.service.impl;

import com.yusys.dao.GoodsDao;
import com.yusys.dao.SaleDao;
import com.yusys.domain.Goods;
import com.yusys.domain.Sale;
import com.yusys.excep.NotEnoughException;
import com.yusys.service.BuyGoodsService;

public class BuyGoodsServiceImpl implements BuyGoodsService {

    private SaleDao saleDao;

    private GoodsDao goodsDao;

    @Override
    public void buy(Integer goodsId, Integer nums) {
        // 记录销售信息，向sale表添加记录
        Sale sale = new Sale();
        sale.setGid(goodsId);
        sale.setNums(nums);
        saleDao.insertSale(sale);

        Goods goods = goodsDao.selectGoods(goodsId);
        if (goods == null) {
            throw new NullPointerException("商品不存在");
        } else if (goods.getAmount() < nums) {
            throw new NotEnoughException("商品库存不足");
        }

        Goods byGoods = new Goods();
        byGoods.setId(goodsId);
        byGoods.setAmount(nums);
        goodsDao.updateGoods(byGoods);
    }

    public void setSaleDao(SaleDao saleDao) {
        this.saleDao = saleDao;
    }

    public void setGoodsDao(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }
}
